import UIKit
//下标脚本可以定义在类，结构体，枚举中。是访问对象，集合或序列的快捷方式
//下标语法
//subscript(index: Int) -> Int {
//    get {}
//    set(newValue){
//        
//    }
//}

struct TimesTable {
    let multipier:Int
    subscript(index:Int) -> Int {
        return multipier * index
    }
}
let threeTimeTable = TimesTable(multipier: 3)
threeTimeTable[6]

 
struct Matix {
    let rows:Int, columns:Int
    var gird:[Double]
    init(rows: Int, columns: Int) {
        self.rows = rows
        self.columns = columns
        self.gird = Array(repeating: 0 , count:rows * columns )
    }
    
    
    func indexIsValid(row:Int, col:Int) -> Bool {
        return row >= 0 && row < rows && col >= 0 && col < columns
    }
    
    subscript(row:Int, col:Int) -> Double {
        get {
            assert(indexIsValid(row: row, col: col), "index out of range")
            return gird[row * columns + col]
        }
        
        set(newValue) {
            assert(indexIsValid(row: row, col: col), "index out of range")
            gird[row * columns + col] = newValue
        }
    }
}

var matrix = Matix(rows: 3, columns: 3)
matrix[0, 2] = 1.5
matrix[2, 0] = 3.2

print("grid now is \(matrix.gird)")
